package io.finer.erp.jeecg.jolimark.model;

import io.finer.erp.jeecg.jolimark.comm.Md5;

import java.io.Serializable;
import java.util.Date;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Access Token请求参数
 * 
 * @author Jolimark
 *
 */
public class AccessTokenRequestModel implements Serializable {
	private static final long serialVersionUID = 4324393391015598535L;
	/**
	 * 应用ID
	 */
	private String appId;
	/**
	 * 签名类型，默认是MD5
	 */
	private String signType;
	/**
	 * 时间戳
	 */
	private String timeStamp;
	/**
	 * 密钥
	 */
	private String key;
	/**
	 * 签名
	 */
	private String sign;

	/**
	 * Access Token请求参数
	 * 
	 * @param appId 应用ID
	 * @param key   密钥
	 */
	public AccessTokenRequestModel(String appId, String key) {
		setAppId(appId);
		setKey(key);
		setSignType("MD5");
	}

	/**
	 * 构建一个有序的请求参数键值对字符
	 * 
	 * @return 有序的请求参数键值对字符
	 */
	public String buildRequestParameter() {
		SortedMap<String, String> map = new TreeMap<String, String>();
		map.put("app_id", getAppId());
		map.put("sign_type", getSignType());
		map.put("time_stamp", String.valueOf(new Date().getTime() / 1000));

		String paramString = convert(map);
		paramString += "key=" + getKey();

		String signString = Md5.encrypt(paramString);

		setSign(signString);
		paramString += "&sign=" + signString;

		return paramString;
	}

	private String convert(SortedMap<String, String> map) {
		StringBuilder result = new StringBuilder();
		Set<Entry<String, String>> items = map.entrySet();

		for (Entry<String, String> entry : items) {
			result.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
		}

		return result.toString().trim();
	}

	public String getAppId() {
		return appId;
	}

	private void setAppId(String appId) {
		this.appId = appId;
	}

	public String getSignType() {
		return signType;
	}

	private void setSignType(String signType) {
		this.signType = signType;
	}

	public String getTimeStamp() {
		return timeStamp;
	}

	public void setTimeStamp(String timeStamp) {
		this.timeStamp = timeStamp;
	}

	public String getKey() {
		return key;
	}

	private void setKey(String key) {
		this.key = key;
	}

	public String getSign() {
		return sign;
	}

	private void setSign(String sign) {
		this.sign = sign;
	}
}
